package com.fmsz.xmly.activitys;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioGroup;

import com.fmsz.xmly.R;
import com.fmsz.xmly.fragments.DownloadFragment;
import com.fmsz.xmly.fragments.FindFragment;
import com.fmsz.xmly.fragments.MyselfFragment;
import com.fmsz.xmly.fragments.SubscriptionFragment;
import com.fmsz.xmly.service.PlayService;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener{
    private RadioGroup home_rg;
    private List<Fragment> fgtList=new ArrayList<>();
    private Fragment[] fgt;
    private int preIndex;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initView();
        initFgt();
    }
//实例化fragment
    private void initFgt() {
        FindFragment findFgt=new FindFragment();
        SubscriptionFragment subFgt=new SubscriptionFragment();
        DownloadFragment downFgt=new DownloadFragment();
        MyselfFragment myFgt=new MyselfFragment();
        fgt=new Fragment[]{findFgt,subFgt,downFgt,myFgt};
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.home_container,fgt[0]);
        transaction.commit();
        changeFgt(0);
    }
//实例化布局
    private void initView() {
        home_rg=(RadioGroup) findViewById(R.id.home_rg);
        home_rg.setOnCheckedChangeListener(this);
    }
    //RadioGroup点击监听
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.find_home_rb:
                changeFgt(0);
                break;
            case R.id.subscription_home_rb:
                changeFgt(1);
                break;
            case R.id.download_home_rb:
                changeFgt(2);
                break;
            case R.id.myself_home_rb:
                changeFgt(3);
                break;
        }
    }

    private void changeFgt(int current) {
        if (current==preIndex) {
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.hide(fgt[preIndex]);
        if (!fgt[current].isAdded()) {
            transaction.add(R.id.home_container,fgt[current]).show(fgt[current]);
        }else{
            transaction.show(fgt[current]);
        }
        transaction.commit();
        preIndex=current;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(this, PlayService.class);
        stopService(intent);
    }
}
